<?php

namespace app\common\logic;

use app\common\model\commonModel;
use app\common\model\trCoupon;
use app\common\model\trUser;
use app\common\util\Tools;
use think\Db;

/**
 * Class Sms
 * 优惠券逻辑类
 * @package Admin\Controller
 */
class CouponLogic
{
    // 发放普通优惠券
    public static function addUserCouponByTemplate($couponId, $couponData = []){
        if(empty($couponData)){
            $couponModel = new trCoupon();
            $couponData = $couponModel->getFields("*", ["id" => $couponId], true, false);
        }
        if($couponData["mold"] == "1" && $couponData["status"] == "1") { // 普通模式自动发送到用户优惠券表里
            $couponData["timeTo"] = is_numeric($couponData["timeTo"]) ? $couponData["timeTo"] : strtotime($couponData["timeTo"]);
            if(time() < $couponData["timeTo"]) {
                $userModel = new trUser();
                if ($couponData["condition"] == "1") { // 使用条件：新注册用户
                    $idList = $userModel->getColumn("id", [["amount", "<=", 0], ["mall_id", "=", request()->mallData["id"]]]);
                } else if ($couponData["condition"] == "2") { // 使用条件：订单金额满足
                    $idList = $userModel->getColumn("id", ["mall_id" => request()->mallData["id"]]);
                } else if ($couponData["condition"] == "3") { // 使用条件：指定用户
                    $idList = $couponData["content"] ? explode(",", $couponData["content"]) : [];
                } else if ($couponData["condition"] == "4") {
                    $idList = $userModel->getColumn("id", ["mall_id" => request()->mallData["id"]]);
                }
                if (!empty($idList) && !commonModel::getCount(userCouponTable, ["coupon_id" => $couponId, "mall_id" => request()->mallData["id"]])) {
                    foreach ($idList as $id) {
                        $insertData[] = [
                            "user_id" => $id, "coupon_id" => $couponId, "type" => $couponData["type"], "mold" => $couponData["mold"],
                            "name" => $couponData["name"], "condition" => $couponData["condition"], "amount" => $couponData["amount"],
                            "mall_id" => request()->mallData["id"], "content" => $couponData["content"],
                            "get_time" => time(), "status" => 1, "end_time" => $couponData["timeTo"]
                        ];
                    }
                    if(!empty($insertData)) {
                        try {
                            if (!Db::name(userCouponTable)->insertAll($insertData)) {
                                return false;
                            }
                        } catch (\Exception $e) {
                            $count = count($insertData);
                            if (!Db::name(userCouponTable)->insertAll(array_slice($insertData, 0, ceil($count / 2))) ||
                                !Db::name(userCouponTable)->insertAll(array_slice($insertData, ceil($count / 2)))) {
                                return false;
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    // 新注册用户发放普通优惠券
    public static function addUserCouponByNewLogin($userId){
        $couponModel = new trCoupon();
        $couponData = $couponModel->getFields("*", [
            ["mold", "=", 1], ["time_to", ">", date("Y-m-d")], ["status", "=", "1"], ["mall_id", "=", request()->mallData["id"]]
        ], false, false);
        if(!empty($couponData)) {
            foreach ($couponData as $couponDatum) {
                if(empty($couponDatum["condition"]) || $couponDatum["condition"] > 4){ // 条件错误就去除
                    continue;
                }
                if ($couponDatum["condition"] == "3" && !in_array($userId, explode(",", $couponDatum["content"]))) { // 使用条件：指定用户
                    continue;
                }
                $couponDatum = Tools::transferFields($couponDatum->getData());
                if(!commonModel::getCount(userCouponTable, ["coupon_id" => $couponDatum["id"], "user_id" => $userId])) {
                    $couponDatum["timeTo"] = is_numeric($couponDatum["timeTo"]) ? $couponDatum["timeTo"] : strtotime($couponDatum["timeTo"]);
                    commonModel::toAdd(userCouponTable, [
                        "user_id" => $userId, "coupon_id" => $couponDatum["id"], "type" => $couponDatum["type"], "mold" => $couponDatum["mold"],
                        "name" => $couponDatum["name"], "condition" => $couponDatum["condition"], "mall_id" => $couponDatum["mallId"],
                        "amount" => $couponDatum["amount"], "content" => $couponDatum["content"],
                        "get_time" => time(), "status" => 1, "end_time" => $couponDatum["timeTo"]
                    ]);
                }
            }
        }
        return true;
    }

    // 发放推荐优惠券
    public static function addUserCouponByRecommend($userId, $couponId = 0, &$msg = ''){
        if(!empty($couponId)){
            $filter = [["id", "=", $couponId], ['status', '=', 1], ["mall_id", "=", request()->mallData["id"]]];
        }else{
            $filter = [['mold', '=', 2], ['status', '=', 1], ["mall_id", "=", request()->mallData["id"]]]; // 推荐类型，推荐者获取优惠券
        }
        $couponModel = new trCoupon();
        $couponData = $couponModel->getFields('*', $filter, true, false);
        if (empty($couponData)){
            $msg = "优惠券不存在";
            return false;
        }
        $timeTo = is_numeric($couponData["timeTo"]) ? $couponData["timeTo"] : strtotime($couponData["timeTo"]);
        $insertData = [
            "user_id" => $userId, "coupon_id" => $couponData["id"], "type" => $couponData["type"], "mold" => $couponData["mold"],
            "name" => $couponData["name"], "condition" => $couponData["condition"], "mall_id" => $couponData["mallId"],
            "amount" => $couponData["amount"], "content" => $couponData["content"],
            "get_time" => time(), "end_time" => $timeTo, "status" => 1
        ];
        $res = commonModel::toAdd(userCouponTable, $insertData);
        if(isset($res["code"]) || !$res){
            $msg = isset($res["msg"]) ? $res["msg"] : "添加优惠券失败";
            return false;
        }
        return true;
    }

    // 获取用户可以使用的优惠券
    public static function getUsableList($userId, $type = 0, $money = 0){
        $filter = [
            ["status", "=", 1], ["user_id", "=", $userId],
            ["get_time", "<=", time()], ["end_time", ">=", time()],
            ["mall_id", "=", request()->mallData["id"]]
        ];
        if(!empty($type)){
            $type = $type != '0' ? $type . ",0" : $type; // 加入通用券
            $filter[] = ["type", "in", $type]; // 1：机场券、2：巴士线路券、3：专车接送券、4包车线路，0通用券
            $field = "id as userCouponId,coupon_id as id,name,amount,condition,content,get_time as time_from,end_time as time_to,type,mold";
        }else{
            $field = "id as userCouponId,coupon_id as id,name,amount,condition,content,get_time as time_from,end_time as time_to,type,mold";
        }
        $couponData = commonModel::getList(userCouponTable, $field, $filter, 0, 0, "get_time desc", false);
        if(!empty($couponData)) {
            $couponModel = new trCoupon();
            foreach ($couponData as $k => $item) {
                $item["condition"] = intval($item["condition"]);
                if(empty($item["condition"])){ // 条件错误就去除
                    unset($couponData[$k]);
                    continue;
                }
                if ($item["condition"] == "2" && $money && floatval($item["content"]) > $money) { // 使用条件：订单金额满足
                    unset($couponData[$k]);// 不满足去掉
                    continue;
                }
                $couponData[$k]["typeText"] = $couponModel->getAttrByType($item["type"]);
                $couponData[$k]["moldText"] = $couponModel->getAttrByMold($item["mold"]);
                $couponData[$k]["timeFrom"] = date("Y-m-d", $item["timeFrom"]);
                $couponData[$k]["timeTo"] = date("Y-m-d", $item["timeTo"]);
            }
        }else{
            $couponData = [];
        }
        return $couponData;
    }

    //获取已使用优惠券列表
    public static function getUseList($userId, $type = 0){
        $filter = [
            ["status", "=", 2], ["user_id", "=", $userId], ["mall_id", "=", request()->mallData["id"]]
        ];
        if(!empty($type)){
            $type = $type != '0' ? $type . ",0" : $type; // 加入通用券
            $filter[] = ["type", "in", $type]; // 1：机场券、2：巴士线路券、3：专车接送券、4包车线路，0通用券
            $field = "id as userCouponId,coupon_id as id,name,amount,condition,content,get_time as time_from,end_time as time_to,type,mold";
        }else{
            $field = "id as userCouponId,coupon_id as id,name,amount,condition,content,get_time as time_from,end_time as time_to,type,mold";
        }
        $useCouponList = commonModel::getList(userCouponTable, $field, $filter, 0, 0, "get_time desc", false);
        if(empty($useCouponList)) {
            $useCouponList = [];
        }else{
            $couponModel = new trCoupon();
            foreach ($useCouponList as $k => $item) {
                $useCouponList[$k]["typeText"] = $couponModel->getAttrByType($item["type"]);
                $useCouponList[$k]["moldText"] = $couponModel->getAttrByMold($item["mold"]);
                $useCouponList[$k]["timeFrom"] = date("Y-m-d", $item["timeFrom"]);
                $useCouponList[$k]["timeTo"] = date("Y-m-d", $item["timeTo"]);
            }
        }
        return $useCouponList;
    }

    // 获取已过期优惠券列表
    public static function getExpireList($userId, $type = 0){
        $filter = [
            ["status", "=", 1], ["user_id", "=", $userId], ["mall_id", "=", request()->mallData["id"]], ["end_time", "<", time()]
        ];
        if(!empty($type)){
            $type = $type != '0' ? $type . ",0" : $type; // 加入通用券
            $filter[] = ["type", "in", $type]; // 1：机场券、2：巴士线路券、3：专车接送券、4包车线路，0通用券
            $field = "id as userCouponId,coupon_id as id,name,amount,condition,content,get_time as time_from,end_time as time_to,type,mold";
        }else{
            $field = "id as userCouponId,coupon_id as id,name,amount,condition,content,get_time as time_from,end_time as time_to,type,mold";
        }
        $couponData = commonModel::getList(userCouponTable, $field, $filter, 0, 0, "get_time desc", false);
        if(!empty($couponData)) {
            $couponModel = new trCoupon();
            foreach ($couponData as $k => $item) {
                $item["condition"] = intval($item["condition"]);
                if(empty($item["condition"])){ // 条件错误就去除
                    unset($couponData[$k]);
                    continue;
                }
                $couponData[$k]["typeText"] = $couponModel->getAttrByType($item["type"]);
                $couponData[$k]["moldText"] = $couponModel->getAttrByMold($item["mold"]);
                $couponData[$k]["timeFrom"] = date("Y-m-d", $item["timeFrom"]);
                $couponData[$k]["timeTo"] = date("Y-m-d", $item["timeTo"]);
            }
        }else{
            $couponData = [];
        }
        return $couponData;
    }
}